<template>
  <el-container id="message-customer-list">
    <el-main>
      <el-container>
        <el-header class="header">
          <div class="breadcrumb">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item>模版消息</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <el-col :span="2">
            <router-link to="/message/template/add">
              <el-button>新增消息</el-button>
            </router-link>
          </el-col>
        </el-header>
      </el-container>
      <el-table
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column
          prop="pushName"
          label="名称">
        </el-table-column>
        <el-table-column
          prop="pushTime"
          label="推送时间">
          <template slot-scope="scope">
            {{formatTime(scope.row.pushTime)}}
          </template>
        </el-table-column>
        <el-table-column
          prop=""
          label="推送范围">
          <template slot-scope="scope">
            {{ scope.row.pushRange === 1 ? '全部粉丝' : ''}}
          </template>
        </el-table-column>
        <el-table-column
          prop=""
          label="数量">
          <template slot-scope="scope">
            {{ scope.row.successNumber + '/' + scope.row.actualNumber }}
          </template>
        </el-table-column>
        <el-table-column
          prop=""
          label="创建人">
          <template slot-scope="scope">
            {{ scope.row.createdUser.nickname || scope.row.createdUser.username || '' }}
          </template>
        </el-table-column>
        <el-table-column
          prop=""
          label="修改人">
          <template slot-scope="scope">
            {{ scope.row.updatedUser ? (scope.row.updatedUser.nickname
            || scope.row.updatedUser.username || '') : '' }}
          </template>
        </el-table-column>
        <el-table-column
          label="推送状态">
          <template slot-scope="scope">
            {{getMessageStatus(scope.row.pushStatus)}}
          </template>
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-button @click="toPreview(scope.row)" type="text" size="small">查看</el-button>
            <el-button @click="toEdit(scope.row.id || '')" type="text" size="small" :disabled="!isEditable(scope.row)">
              编辑
            </el-button>
            <el-button @click="toDelete(scope.row.id || '')" type="text" size="small"
                       :disabled="!isDeletable(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          background
          @size-change="handlePageSizeChange"
          @current-change="handleCurrentPageChange"
          :current-page="page.page + 1"
          :page-sizes="[10, 20, 100, 300, 400]"
          :page-size="20"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.totalElement">
        </el-pagination>
      </div>
    </el-main>
  </el-container>
</template>

<script>
  import moment from 'moment';
  import {mapState, mapActions} from 'vuex';

  import CONSTANT from '../../../constant/common';
  import cookie from '../../../lib/cookie';

  const audioTemplate = '<audio controls><source src="{{$}}"></source></audio>';
  export default {
    data() {
      return {
        userRole: cookie(CONSTANT.COOKIE_USER_ROLE),
      };
    },
    components: {},
    computed: {
      ...mapState({
        tableData: state => state.message.templateMsgList,
        page: state => state.message.templatePage,
      }),
      appId() {
        const localWoa = localStorage.getItem(CONSTANT.STORAGE_LOCAL_WOA) ?
          JSON.parse(localStorage.getItem(CONSTANT.STORAGE_LOCAL_WOA)) : {};
        console.log('get local woa ', localWoa);
        return this.$store.state.woa.currentWoa.appId || localWoa.appId;
      },
    },
    mounted() {
      this.checkAppIdOk({
        appId: this.appId,
      }).then(() => {
        this.getTemplateMessageList({...this.page, appid: this.appId});
      }, () => {
        this.$message.warning('当前公众号暂不可用，请稍后再试或选择其他公众号');
        this.$router.replace('/home');
      });
    },
    methods: {
      ...mapActions([
        'checkAppIdOk',
        'getTemplateMessageList',
        'getTemplateMessage',
        'deleteTemplateMessage',
        'getMpNewsByMediaId',
        'getImageByMediaId',
        'getVoiceByMediaId',
      ]),
      toPreview(item) {
        this.$alert(`<p style="word-break:break-all">${item.pushContent.replace(/(\r\n)/g, '<br>')}</p>`, '模版消息详情', {
          dangerouslyUseHTMLString: true,
          // center: true,
        });
      },
      isEditable(item) {
        return item.pushStatus === 'WAITING';
      },
      isDeletable(item) {
        return item.pushStatus === 'WAITING';
      },
      getMessageStatus(status) {
        if (status === 'WAITING') {
          return '待办';
        }
        if (status === 'FAIL') {
          return '失败';
        }
        if (status === 'PUSHING') {
          return '推送中';
        }
        if (status === 'COMPLETE') {
          return '已完成';
        }
        if (status === 'INVALID') {
          return '失败';
        }
        return '未知状态';
      },
      handlePageSizeChange(val) {
        this.getTemplateMessageList({...this.page, size: val, appid: this.appId});
      },
      handleCurrentPageChange(val) {
        this.getTemplateMessageList({...this.page, page: (val - 1), appid: this.appId});
      },
      formatTime(stamp) {
        return stamp ? moment(stamp).format('YYYY-MM-DD HH:mm:ss') : '立即推送';
      },
      formatFinishTime(stamp) {
        return stamp ? moment(stamp).format('YYYY-MM-DD HH:mm:ss') : '--';
      },
      toDelete(id) {
        this.$confirm('删除该条消息模版，请确认操作', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true,
        }).then(() => {
          this.deleteTemplateMessage({
            id,
            appid: this.appId,
          }).then(() => {
            this.$message({
              type: 'success',
              message: '删除成功',
            });
            setTimeout(() => {
              this.getTemplateMessageList({...this.page, appid: this.appId});
            }, 20);
          }).then((e) => {
            this.$message({
              type: 'error',
              message: `删除失败->${e.message}`,
            });
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消',
          });
        });
      },
      toEdit(id) {
        this.$router.push({
          path: `/message/template/add`,
          query: {id}
        });
      },
    },
  };
</script>

<style lang="less">
  #message-customer-list {
    font-family: Helvetica, sans-serif;
    width: 100%;
    height: 100%;
    position: relative;

    .header {
      display: flex;
      justify-content: space-between;

      .breadcrumb {
        height: 40px;
      }
    }

    .page {
      position: absolute;
      bottom: -20px;
      right: 20px;
    }
  }

  .el-message-box__content {
    max-height: 600px;
    overflow: auto;
  }
</style>
